package com.loit.business.utils;


import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 
 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 
import java.io.IOException; 
import java.io.StringReader; 
import java.io.StringWriter; 
import java.io.Writer; 
/**
 *
 * @author dongliang
 * 格式化XML文
 */
public class XmlFormatter { 
    public static String format(String unformattedXml) {
        try { 
            final Document document = parseXmlFile(unformattedXml); 
            OutputFormat format = new OutputFormat(document);
            format.setLineWidth(65); 
            format.setIndenting(true); 
            format.setIndent(2); 
            Writer out = new StringWriter(); 
            XMLSerializer serializer = new XMLSerializer(out, format);
            serializer.serialize(document); 
            return out.toString(); 
        } catch (IOException e) { 
            throw new RuntimeException(e); 
        } 
    } 
    private static Document parseXmlFile(String in) {
        try { 
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
            DocumentBuilder db = dbf.newDocumentBuilder(); 
            InputSource is = new InputSource(new StringReader(in)); 
            return db.parse(is); 
        } catch (ParserConfigurationException e) { 
            throw new RuntimeException(e); 
        } catch (SAXException e) { 
            throw new RuntimeException(e); 
        } catch (IOException e) { 
            throw new RuntimeException(e); 
        } 
    } 
    public static void main(String[] args) throws Exception{ 
        String s = "<?xml version=\"1.0\" encoding=\"utf-8\"?><pReq><pBidNo>BH20150528020858250699</pBidNo><pContractNo>HT20150528020858367027</pContractNo><pBidType>8</pBidType><pOutType>1</pOutType><pUse>资金周转</pUse><pMerBillNo>GB20150529045854664098102</pMerBillNo><pBidDate>20150529</pBidDate><pDeadLine>99999</pDeadLine><pAgreementNo></pAgreementNo><pFAcctType>1</pFAcctType><pFIdentType>1</pFIdentType><pFIdentNo>32038119960417351X</pFIdentNo><pFRealName>张三</pFRealName><pFIpsAcctNo>4021000123494969</pFIpsAcctNo><pTAcctType>1</pTAcctType><pTIdentType>1</pTIdentType><pTIdentNo>310223196607042414</pTIdentNo><pTRealName>李四</pTRealName><pTIpsAcctNo>4021000120388120</pTIpsAcctNo><pTrdAmt>50.0</pTrdAmt><pFTrdFee>0</pFTrdFee><pTTrdFee>55.15</pTTrdFee><pWebUrl>https://localhost/plank/returnBid.htm</pWebUrl><pS2SUrl>https://localhost/processing/asynchronismBid.htm</pS2SUrl><pMemo1>102</pMemo1><pMemo2>235</pMemo2><pMemo3>55.15</pMemo3></pReq>";
        System.out.println(format(s));
         
    } 
} 